<?php


namespace Catmes\HttpClient;


class Response
{

    protected $rawData='';
    protected $body='';
    protected $headersRaw='';
    protected $headers=[];
    protected $headersMap=[];
    protected $httpVersion=''; // HTTP/1.1
    protected $statusCode=0;

    public function __construct($responseRaw){
        $this->rawData = $responseRaw;
        // 剥离响应头和响应体
        list($headersStr,$contentStr)=explode("\r\n\r\n",$responseRaw,2);
        $this->headersRaw = $headersStr;
        $this->body = $contentStr;
        // 剥离每一条响应头
        $headers = explode("\r\n", $this->headersRaw);
        $this->headers = $headers;
        // 提取状态码
        $statusInfo = explode(" ", $headers[0]);
        $this->httpVersion = $statusInfo[0];
        $this->statusCode = $statusInfo[1];
        // 解析响应头详情
        $info = [];
        foreach ($this->headers as $key => $header){
            if($key>0){
                $headerArr = explode(": ", $header);
                $info[$headerArr[0]] = $headerArr[1];
            }
        }
        $this->headersMap = $info;
    }

    /**
     * 获取原始响应头和响应体
     * @return string
     */
    public function getRawData(){
        return $this->rawData;
    }

    /**
     * 获取响应消息主体
     * @return string
     */
    public function getBody(){
        return $this->body;
    }

    /**
     * 获取原始响应头
     * @return string
     */
    public function getHeadersRaw(){
        return $this->headersRaw;
    }

    /**
     * 获取数组格式的响应头
     * @return array
     */
    public function getHeadersList(){
        return $this->headers;
    }

    /**
     * 获取响应头键值对
     * @return array
     */
    public function getHeadersMap(){
        return $this->headersMap;
    }

    /**
     * 获取响应头字段的对应值
     * @return string | null
     */
    public function getHeaderValue($key){
        if(isset($this->headersMap[$key])){
            return $this->headersMap[$key];
        }
        return null;
    }

    /**
     * 获取响应状态码
     * @return integer
     */
    public function getStatusCode(){
        return $this->statusCode;
    }

    public function toArray(){
        $array = json_decode($this->getBody(),true);
        if($array){
            return $array;
        }
        return false;
    }

    public function __toString(){
        return $this->getBody();
    }

}